package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 拦截器
* */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        //判断是否是OPTIONS请求，如果是就返回TRUE
        if (HttpMethod.OPTIONS.toString().equals(req.getMethod())) {
            log.info("是OPTIONS请求,放行");
            return true;
        }
        //1.获取请求的url
        String url = req.getRequestURI();
        log.info("请求的url为: {}",url);

        //2.判断请求的url中是否包含login,如果包含说明是登录操作则放行
        if (url.contains("login")){
            log.info("请求为登录操作,放行");
            return true;
        }
        if (url.contains("/api/tile/reqstream")){
            log.info("请求为登录操作,放行");
            return true;
        }
        if (url.contains("/error")){
            log.info("请求为登录操作,放行");
            return true;
        }
        //3.获取请求头中的令牌
        String token = req.getHeader("Token");

        //4.判断令牌是否存在,如果不存在,返回错误结果(未登录)

        if (!StringUtils.hasLength(token)){
            log.info("请求头token为空,返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            String notlogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notlogin);
            return false;
        }
//        5.解析token,如果解析失败,回错误结果(未登录)
        try {
            JwtUtils.ParseJwt(token);
        } catch (Exception e) {  //解析失败
            e.printStackTrace();
            log.info("解析令牌失败,返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            String notlogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notlogin);
            return false;
        }
        //6.放行
        return true;
    }

}
